package com.gree.elasticsearch.security.requestmatcher;

import io.jsonwebtoken.lang.Assert;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

public class SkipRequestMatcher implements RequestMatcher {
    private OrRequestMatcher orRequestMatcher;
    private List<String> skipUri;
    private RequestMatcher processUriMatcher;

    public SkipRequestMatcher(List<String> skipUri, String processUri) {
        Assert.notNull(skipUri, "skipUri parameter is must not null or size is zero");

        List<RequestMatcher> requestMatchers = skipUri.stream().map(uri -> {
            RequestMatcher requestMatcher = new AntPathRequestMatcher(uri);
            return requestMatcher;
        }).collect(Collectors.toList());

        this.orRequestMatcher = new OrRequestMatcher(requestMatchers);

        this.processUriMatcher = new AntPathRequestMatcher(processUri);
    }

    @Override
    public boolean matches(HttpServletRequest httpServletRequest) {
        if (orRequestMatcher.matches(httpServletRequest)) {
            return Boolean.FALSE;
        }

        if (processUriMatcher.matches(httpServletRequest)) {
            return Boolean.TRUE;
        }

        return Boolean.FALSE;
    }
}
